package com.woniu.zsd.user.consumer;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.woniu.commons.util.RedisKey;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Component
public class RabbitMQConsumer {
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Value("${huyi.api}")
    private String api;

    @RabbitListener(queues = "register-code-queue")
    @RabbitHandler
    public void sendCode(String phone) throws Exception {
        System.out.println("从队列中取出手机号：" + phone);
        // 检查是否已经存在未过期的验证码
        String existingCode = stringRedisTemplate.opsForValue().get(RedisKey.SEND_REGISTER_CODE_KEY(phone));
        if (existingCode != null) {
           return;
        }
        // 发送验证码
        HashMap<String, Object> params = new HashMap<>();
        params.put("account", "C71845584");
        params.put("password", "0c8325cce46d0f53434251d7fa9813af");
        params.put("mobile", phone);
        params.put("format", "json");
        int code = (int) (Math.random() * 9000) + 1000;
        System.out.println(code);
        String content = "您的验证码是：" + code + "。请不要把验证码泄露给其他人。";
        params.put("content", content);
        //向第三方的接口发送请求
        HttpResponse response = HttpRequest.post(api).form(params).execute();
        String json = response.body();
        String resultCode = JSONUtil.parseObj(json).get("code").toString();

        if ("2".equals(resultCode)) {
            stringRedisTemplate.opsForValue().set(RedisKey.SEND_REGISTER_CODE_KEY(phone), String.valueOf(code), 300, TimeUnit.SECONDS);
            stringRedisTemplate.opsForValue().set(RedisKey.REGISTER_LAST_SEND_TIME_KEY(phone), String.valueOf(new Date().getTime()), 60, TimeUnit.SECONDS);
        }
    }
}